<?php
/**
* 身份角色
* @author darker <416319808@qq.com>
*/
namespace app\common\model;
use think\Model;

class Role extends Model
{
	
	/**
	 * 某个
	 * @param  integer $id 
	 * @return [type]     [description]
	 */
	public function getRolesById($id = null)
	{
		if ($id) {
			
		}

		$data = self::all(function ($query)
    	{
    		$query->field('*')->order('id');
    	});
		return eltree($data);
	}


	/**
	 * 设置角色
	 * @param array $data 表单数据
	 */
	public function setRole($data)
	{
		if ($data['id']) {
			return self::update($data);
		}

		return self::insert($data);
	}


	/**
	 * 根据身份获取用户
	 * @param  integer $id 身份id
	 * @param  boolean $flag 为true的时候按pid查
	 * @return array
	 */
	public function getUserById($id, $flag = false)
	{
		$map = [
			'a.is_del' => 0,
			'b.auth' => 1,
			'c.ban' => 0
		];

		if ($flag) {
			$map['a.pid'] = $id;
		} else {
			$map['a.id'] = $id;
		}

		$data = $this->alias('a')
					->where($map)
					->join('relation b', 'a.id = b.rid')
					->join('user c', 'b.uid = c.uid')
					->field('c.uid,c.name,c.phone')
					->select();
		
		return endoceArr($data);					
	}

	
	public function level($uid) {
		$data = $this->alias('a')
			->where(['b.uid' => $uid])
			->join('relation b', 'a.id = b.rid')
			->field('id,pid,name')
			->select();

		foreach ($data as $index => $item) {
			$data[$index]['parent'] = $this->getUserById($item['pid']);
			$data[$index]['children'] = $this->getUserById($item['id'], true);
		}

		return $data;
	}

}